
import {handleAsChord} from "./keyboard.js";
import {first, last} from "underscore";
import {$} from "../util/seq.js";
import {focusableElements} from "./focusable.js";

function isTabbable() {
    return this.tabIndex >= 0;
}

function tabbableElements(container) {
    return container.selectAll(focusableElements).filter(isTabbable);
}

function tabBounds(container) {
    const tabbable = tabbableElements(container).nodes();
    return [first(tabbable), last(tabbable)];
}

/**
 * @param container d3 selection whose tabbable descendents form a tabbing loop (i.e., tabbing from the last
 *        descendent causes focus to move to the first descendent).
 */
export function defineTabbingLoop(container) {

    const bounds = tabBounds(container);

    container.on($`keydown`, handleAsChord((chord, {target}) => {
        switch (chord) {
            case "Tab":       return target === bounds[1] ? (bounds[0].focus(), true) : false;
            case "Shift-Tab": return target === bounds[0] ? (bounds[1].focus(), true) : false;
        }
    }));

}
